import {addComment} from '../../../api/evaluate'

// pages/mine/evaluate/evaluate.js
Page({

 /**
   * 页面的初始数据
   */
  data: {
    comment:{
      userId:'',//用户id
      status:0,//状态 0-正常 1-匿名
      content:'',
      score:3,
      productType:'',
      productId:'',
      commentImg:'',
      token:'',
      user:{},
  
    },
    // 媒体配置
    maxImageCount: 3, // 最大图片数
    uploadedImages: [], // 初始为空数组
    newImages:[],
    error: {
      image: '' // 初始不显示错误
    },
    content: '', // 评价内容
    anonymous: false, // 匿名开关
    orderid:0, //订单编号
    token:'',
    user:{},
  },

  // 选择图片
  handleChooseImage() {
    const remainCount = this.data.maxImageCount - this.data.uploadedImages.length;
    wx.chooseImage({
      count: remainCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          uploadedImages: [...this.data.uploadedImages, ...res.tempFilePaths],
          'error.image': '' // 清除错误
        });
      }
    });
  },

  // 删除图片
  handleDeleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const newImages = this.data.uploadedImages.filter((_, i) => i !== index);
    this.setData({ uploadedImages: newImages });
  },

  //上传图片方法
  uploadAvatar(filePath) {
    const that = this;
    wx.uploadFile({
      url: 'http://127.0.0.1:8024/wx/upload', 
      filePath: filePath,
      name: 'file',
      success(uploadRes) {
        // console.log('头像上传成功', uploadRes);
        let data=JSON.parse(uploadRes.data)
        console.log(data)
        let list=[...that.data.newImages]
        that.setData({
          newImages:list.concat(data.data.url)
        })
        console.log(that.data.newImages)
      },
      fail(err) {
        console.error('图片上传失败', err);
      }
    });
  },


  // 选择星级
  handleSelectStar(e) {
    this.setData({ 
      'comment.score': e.detail 
    });
    console.log(this.data.comment.score)
  },

  // 评价内容输入
  handleContentInput(e) {
    this.setData({ 'comment.content': e.detail.value });
  },

  // 提交评价
  handleSubmit() {
    // 表单验证
    if (this.data.comment.score === 0) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      });
      return;
    }

    if (!this.data.comment.content.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      });
      return;
    }

    if(this.data.anonymous==false){
      this.setData({
        'comment.status':0
      })
    }else{
      this.setData({
        'comment.status':1
      })
    }
    console.log(this.data.comment)
    
    //接口请求
    wx.showLoading({ title: '提交中...' });
    //循环上传图片
    this.data.uploadedImages.forEach((item)=>{
      this.uploadAvatar(item)
    })
    setTimeout(()=>{
      console.log(this.data.comment)
      this.setData({
        'comment.commentImg':this.data.newImages.toString()
      })
      //新增
      addComment(this.data.comment).then(data=>{
        console.log(data)
      })
      wx.hideLoading();
      wx.showToast({ title: '评价提交成功' });
      // wx.navigateBack();
      // 打开反馈页时使用 navigateTo，保留订单页在栈中
      wx.navigateTo({
        url: '/pages/mine/payment/payment?tabid=3'
      })
    }, 3000)
  },
  changeChecked(e){
    this.setData({
      anonymous:!this.data.anonymous
    })
    console.log(this.data.anonymous)
  },

  onusers(){
    const userInfo=wx.getStorageSync('userInfo');
    const token=wx.getStorageSync('token')
    if(token!=null){
      this.setData({
        user:userInfo,
        token
      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    //获得用户信息
    this.onusers()
    this.setData({
      'comment.userId':wx.getStorageSync('userInfo').userId
    })
    console.log(this.data.comment)

    //获得订单相关信息
    console.log(options)
    this.setData({
      'comment.productId':options.productid,
      'comment.productType':options.producttype,
      orderid:options.orderid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})